package model

import (
	"fmt"

	jwt "github.com/dgrijalva/jwt-go/v4"

	"alolang.org.cn/api/server/config"
)

type JWT struct {
	SigningKey []byte
}

func NewJWT() *JWT {
	return &JWT{
		[]byte(config.Server.Security.JWTSecret),
	}
}

type UserClaims struct {
	UserID   uint
	UserName string
	Role     int
	jwt.StandardClaims
}

func (j *JWT) CreateToken(claims UserClaims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS384, claims)
	return token.SignedString(j.SigningKey)
}

func (j *JWT) ParseToken(tokenString string) (*UserClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &UserClaims{},
		func(token *jwt.Token) (interface{}, error) { return j.SigningKey, nil })
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*UserClaims); ok && token.Valid {
		return claims, nil
	}
	return nil, fmt.Errorf("invalid token")
}
